<template>
    <div>
        <n-space vertical :size="12">
            <n-space>
                <n-input v-model:value="state.query.keyword" type="text"
                         placeholder="搜索"  :clearable="true"
                         @keyup.enter="getDataList"/>
                <n-button @click="getDataList" type="default" ghost>查询</n-button>
                <!--      <n-button @click="clearSorter" type="info">重置</n-button>-->
                <n-button @click="addUserHandle()" type="info" ghost>新增</n-button>
                <n-button @click="deleteBatchHandle()" type="error" ghost>删除</n-button>
            </n-space>

            <n-data-table
                size="medium"
                :columns="columns"
                :data="state.result"
                :pagination="pagination"
            />
        </n-space>
        <n-drawer v-model:show="show" :width="500" :close-on-esc="true" :mask-closable="false">
            <n-drawer-content>
                <template #header>
                    用户信息
                </template>
                <n-form
                    ref="formRef"
                    label-placement="left"
                    label-width="auto"
                    :model="formValue"
                    :rules="rules">
                    <!--                :size="medium"-->
                    <!--            >-->
                    <n-form-item label="用户名" path="username">
                        <n-input v-model:value="formValue.username" placeholder="输入用户名"/>
                    </n-form-item>
                    <n-form-item label="姓名" path="name">
                        <n-input v-model:value="formValue.name" placeholder="输入姓名"/>
                    </n-form-item>
                    <n-form-item label="电话号码" path="phone">
                        <n-input v-model:value="formValue.phone" placeholder="电话号码"/>
                    </n-form-item>
                    <n-form-item label="TOKEN" path="token">
                        <n-input v-model:value="formValue.token" placeholder="token" readonly/>
                    </n-form-item>
                    <!--                <n-form-item>-->
                    <!--                    <n-button attr-type="button" @click="handleValidateClick">-->
                    <!--                        验证-->
                    <!--                    </n-button>-->
                    <!--                </n-form-item>-->
                </n-form>
                <template #footer>
                    <n-flex justify="space-between" style="width: 100%">
                        <n-button @click="cancelClicked" ghost type="error">
                            关闭
                        </n-button>
                        <n-button @click="saveClicked" ghost type="primary">
                            保存
                        </n-button>
                    </n-flex>
                </template>
            </n-drawer-content>
        </n-drawer>
    </div>
</template>

<script setup lang="ts">
import {type FormInst, NButton, NPopconfirm, NSwitch} from 'naive-ui'
import {h, onMounted, reactive, ref} from "vue";
import {
    deleteUser,
    getUserById,
    getUserList,
    resetPassword,
    saveUser,
    switchUserEnabled,
    updateUser
} from "@/api/sm/user.ts";
import {switchPipelineEnabled} from "@/api/pm/pipeline.ts";

const state = reactive({
    query: {
        keyword: ''
    },
    result: [],
})

let editType = "new"
const show = ref(false)
const formRef = ref<FormInst | null>(null)
const formValue = ref({
    id: '',
    username: '',
    name: '',
    phone: '',
    token: '',
})
const rules = {
    name: {
        required: true,
        message: '姓名不能为空',
        trigger: ['input', 'blur']
    },
    username: {
        required: true,
        message: '登录名不能为空',
        trigger: ['input', 'blur']
    },
    phone: {
        required: true,
        message: '电话号码不能为空',
        trigger: ['input', 'blur']
    }
}
// const buttonNames = [
//     {
//         title: "删除",
//         icon: CloseIcon,
//         type: "error"
//     }, {
//         title: "详情",
//         icon: InfoIcon,
//         type: "info"
//     }
// ]
const columns = [
    {
        title: '启用',
        key: 'enabled',
        width: 60,
        render(row) {
            return h(
                NSwitch,
                {
                    value: row.enabled, size: 'small', onUpdateValue: () => {
                        switchUserEnabled(row.id)
                        row.enabled = !row.enabled
                        if(row.enabled){
                            window.$message?.success('已启用用户 ['+row.name+']')
                        } else {
                            window.$message?.info('已禁用用户 ['+row.name+']')
                        }
                    }
                }
            )
        },
    },
    {
        title: '姓名',
        key: 'name',
        minWidth: 150
    },
    {
        title: '用户名',
        key: 'username',
        width: 180,
    },
    {
        title: '手机',
        key: 'phone',
        width: 150,
    },
    {
        title: '操作',
        key: 'action',
        width: 300,
        align: "right",
        titleAlign: 'right',
        fixed: 'right',
        render(row) {
            return [
                h(NPopconfirm,
                    {
                        positiveButtonProps: {
                          ghost: true,
                          bordered: true,
                          size: 'tiny',
                          type: 'error',
                        },
                        negativeButtonProps: {
                          ghost: true,
                          bordered: true,
                          size: 'tiny',
                        },
                        onPositiveClick: () => {
                            deleteUser(row.id).then((res: any) => {
                                if (res.code != 200) {
                                    window.$message?.error(res.message)
                                } else {
                                    window.$message?.success(res.message)
                                    console.log(res.message)
                                    getDataList();
                                }
                            })
                        },
                        negativeText: "取消",
                        positiveText: "删除"
                    },
                    {
                        trigger: () => {
                            return h(
                                NButton,
                                {
                                    size: 'small',
                                    style: {
                                        marginLeft: '3px'
                                    },
                                    ghost: true,
                                    type: "error",
                                    bordered: true,
                                    tooltip: '删除',
                                },
                                {default: () => '删除'}
                            )
                        },
                        default: () => {
                            return '确认删除【' + row.name + '】？'
                        }
                    }
                ),
                h(NButton,
                    {
                        size: 'small',
                        style: {
                            marginLeft: '3px'
                        },
                        ghost: true,
                        type: "info",
                        bordered: true,
                        tooltip: "编辑",
                        onClick: () => {
                            getUserById(row.id).then((res: any) => {
                                formValue.value = res.data
                            })
                            editType = "edit"
                            show.value = true
                        }
                    },
                    {default: () => "编辑"}
                ),h(NButton,
                    {
                        size: 'small',
                        style: {
                            marginLeft: '3px'
                        },
                        ghost: true,
                        type: "info",
                        bordered: true,
                        tooltip: "重置密码",
                        onClick: () => {
                            resetPassword(row.id).then((res: any) => {
                                console.log(res)
                                window.$message?.info(res.message)
                            })
                        }
                    },
                    {default: () => "重置密码"}
                )]
        }
    }
]


const pagination = {
    pageSize: 10
}

const getDataList = () => {
    getUserList().then(res => {
        state.result = res.data
        console.log(state.result)
    })
}
// 新增
const addUserHandle = () => {
    formValue.value = {
        id: '',
        username: '',
        name: '',
        phone: '',
        token: '',
    }
    editType = "new"
    show.value = true
}

const deleteBatchHandle = () => {
    window.$message?.error('点击了删除')
}

const cancelClicked = (e: MouseEvent) => {
    show.value = false
}

const saveClicked = (e: MouseEvent) => {
    e.preventDefault()
    formRef.value?.validate((errors) => {
        if (!errors) {
            if (editType == "new") {
                saveUser(formValue.value).then((res: any) => {
                    if (res.code != 200) {
                        window.$message?.error(res.message)
                    } else {
                        window.$message?.success("保存成功")
                        console.log(res.message)
                        show.value = false;
                        getDataList();
                    }
                })
            } else {
                updateUser(formValue.value).then((res: any) => {
                    if (res.code != 200) {
                        window.$message?.error(res.message)
                    } else {
                        window.$message?.success(res.message)
                        console.log(res.message)
                        show.value = false;
                        getDataList();
                    }
                })
            }
        } else {
            console.log(errors.map((e) => e.message))
            window.$message?.error(errors.map((e) => e.message))
        }
    })
}

onMounted(() => {
    getDataList()
})


</script>

<style></style>
